package com.yuanxin.chooseimage;

import android.os.AsyncTask;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.yuanxin.chooseimage.customutil.LocalUtil;

import java.lang.ref.WeakReference;

public class ImageBaseTask extends AsyncTask<ReadableArray, Void, WritableArray> {
    private final WeakReference<Promise> promiseWeakReference;

    public ImageBaseTask(Promise promise) {
        promiseWeakReference = new WeakReference<Promise>(promise);
    }

    /**
     * Override this method to perform a computation on a background thread. The
     * specified parameters are the parameters passed to {@link #execute}
     * by the caller of this task.
     * <p>
     * This method can call {@link #publishProgress} to publish updates
     * on the UI thread.
     *
     * @param params The parameters of the task.
     * @return A result, defined by the subclass of this task.
     * @see #onPreExecute()
     * @see #onPostExecute
     * @see #publishProgress
     */
    @Override
    protected WritableArray doInBackground(ReadableArray... params) {
        WritableArray fileList = Arguments.createArray();
        for (int i = 0; i < params[0].size(); i++) {
            ReadableMap fileInfo = params[0].getMap(i);
            String filePath = fileInfo.getString("filePath");
            double imageWidth = -1;
            double imageHeight = -1;
            int scale = -1;
            int sill = 100;
            if (fileInfo.hasKey("width"))
                imageWidth = fileInfo.getDouble("width");
            if (fileInfo.hasKey("height"))
                imageWidth = fileInfo.getDouble("height");
            if (fileInfo.hasKey("scale"))
                scale = (int) (fileInfo.getDouble("scale") * 100);
            if (fileInfo.hasKey("sill"))//阀值 单位kb，如果文件大于sill，那么根据scale进行压缩，如果文件小于sill，则不压缩，默认值100kb
                sill = fileInfo.getInt("sill");
            WritableMap returnFileInfo = Arguments.createMap();
            returnFileInfo.putString("filePath", filePath);
            returnFileInfo.putString("imageData", LocalUtil.getPirBase(filePath, imageWidth, imageHeight, scale,sill));
            fileList.pushMap(returnFileInfo);
        }
        return fileList;
    }

    @Override
    protected void onPostExecute(WritableArray fileBase) {
        if (promiseWeakReference != null && fileBase != null) {
            final Promise promise = promiseWeakReference.get();
            promise.resolve(fileBase);
        }
    }
}
